<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 
      有时候在微信网页端插入<Video>标签的时候,不希望用户来拖动进度条的话,可以直接使用 playsinline属性,webkit-edlavsinline属性 
    -->
    <video id="video" autoplay playsinline muted></video>
    <button class="btn">打开摄像头</button>
  </body>
  <script>
    // 参考文档：https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia

    const btn = document.querySelector(".btn");
    const video = document.querySelector("#video");

    // 限制
    const limit = {
      audio: true,
      video: {
        width: 500,
        height: 500,
        // 使用前置摄像头
        facingMode: "user",
      },
    };

    // 店家按钮打开摄像头事件
    btn.addEventListener("click", openCamera, false);

    // 打开摄像头处理函数
    function openCamera() {
      navigator.mediaDevices
        .getUserMedia(limit)
        .then(handleSuccess, handleError);
    }

    // 成功的回调
    function handleSuccess(stream) {
      console.log(stream);
      video.srcObject = stream;
    }

    // 失败的回调
    function handleError(error) {
      console.log(error);
    }
  </script>
</html>
